<?php
namespace zhtfrontend\controllers;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\components\helpers\Util;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\models\datas\AuthItem;
use zhtfrontend\models\datas\AuthRule;

/**
 * Created by PhpStorm.
 * User: dongxiaofeng
 * Date: 2018/4/4
 * Time: 11:13
 */
class RuleController extends BaseController{
    //规则管理
    public function actionIndex(){
        $authManager = \Yii::$app->authManager;
        $rules = $authManager->getRules();//获取到所有的规则
        $models = [];
        if(!empty($rules)){
            foreach ($rules as $name=>$item){
                $models[] = new AuthRule($item);
            }
        }
        return $this->render('index',['data'=>$models]);
    }

    //规则添加，自动添加上权限免得多余一步操作
    public function actionCreate(){
        $this->layout='@app/views/layouts/iframe.php';
        $model = new AuthRule(null);
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'rule-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if($model->load(\Yii::$app->request->post()) && $model->validate()){
            if($model->save(false)){
                //创建完了之后，需要创建对应的权限
                $authManager = \Yii::$app->authManager;
                $relatedPermission = $authManager->createPermission($model->name);//创建针对于规则所对应的权限，名字和规则一致
                $relatedPermission->description = $model->name;
                $relatedPermission->ruleName = $model->name;
                $authManager->add($relatedPermission);
                return $this->redirectMessage(\Yii::t('zhtfrontend','规则添加成功'),Fun::url('rule/index'));
            }
        }

        return $this->render('create',['model'=>$model]);
    }

    public function actionUpdate(){
        $this->layout='@app/views/layouts/iframe.php';
        if(\Yii::$app->request->get('name') == null){
            throw new BadRequestHttpException('非法请求');
        }
        $name = \Yii::$app->request->get('name');
        $model = $this->findModel($name);
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'rule-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if($model->load(\Yii::$app->request->post())  && $model->validate()){
            if($model->save(false)){
                \Yii::$app->session->setFlash('success','规则修改成功!');
                return $this->runAction('index');
            }
        }

        return $this->render('update',['model'=>$model]);
    }

    public function actionGeta(){
        $auth = \Yii::$app->authManager;
        $hh = $auth->getChildren("机构管理员规则");
        print_r($hh);exit;
    }
    /*
     * 规则应用于具体的路径
     * 怎么实现，列出目前菜单所有的路径，将要使用的拉到右边
     */
    public function actionAssignpermission(){
        $data = null;
        //phpinfo();exit;
        \Yii::$app->cache->flush();
        if(\Yii::$app->request->get('name') == null){
            throw new BadRequestHttpException('非法请求');
        }
        $rule_permission = \Yii::$app->request->get('name');
        $menu_tree = Fun::cache("menutree_branch_cache");
        $str = "<tr>
					<td align='center'>\$id</td>
					<td align='left'>\$spacer<i class='fa \$icon'></i> \$name</td>
					<td align='center'>\$m</td>
					<td align='center'>\$c</td>
					<td align='center'>\$a</td>
					<td align='center'>\$param</td>
					<td align='center'>\$display</td>
                    <td align='center'>\$frontend_ruleoperate</td>
				</tr>";
        $menu_str = (new Tree(Fun::asArray($menu_tree, ['frontend_ruleoperate']), ['&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ '], '&nbsp;&nbsp;&nbsp;'))->getTreeTable(0, $str);

        return $this->render('assignpermission',['menu_str'=>$menu_str,'rule_permission'=>$rule_permission]);
    }

    public function findModel($name){
        $authmanager = \Yii::$app->authManager;
        $rule = $authmanager->getRule($name);
        if($rule){
            return new AuthRule($rule);
        }else{
            throw new NotFoundHttpException('The requested page does not exist.');
        }

    }

    public function actionAssignmenu(){
        if (\Yii::$app->request->isAjax) {
                \Yii::$app->response->format = Response::FORMAT_JSON;
                $auth = \Yii::$app->authManager;
            if(\Yii::$app->request->post('ajax') == 'getexistpermission'){
                $ajaxObject = new AjaxObject();
                $rule_permission_name = \Yii::$app->request->post('rule_permission');
                $children = $auth->getChildren($rule_permission_name);
                $menu_ids = [];
                if(!empty($children)){
                    foreach ($children as $child){
                        $ai = AuthItem::findOne($child->name);
                        if(!empty($ai)){
                            $menu_ids[] = $ai->menu_id;
                        }
                    }
                }
                $ajaxObject->data = $menu_ids;
                return $ajaxObject;

            }
            if(\Yii::$app->request->post('ajax') == "dosyncoper"){
                $ajaxObject = new AjaxObject();
                $menu_id = \Yii::$app->request->post('id');
                $rule_permission_name = \Yii::$app->request->post('rule_permission');
                $rule_permission = $auth->getRule($rule_permission_name);
                $menu_permission = $this->getMenuPermission($menu_id);
                if(!empty($rule_permission) && !empty($menu_permission)){
                    $type = \Yii::$app->request->post('type');
                    if($type == 'close'){
                        //进行打开操作，将菜单权限作为规则权限的孩子，也就是规则是否应用于这个菜单
                        $auth->addChild($rule_permission,$menu_permission);
                        $result = '打开啦';
                        $ajaxObject->content = $result;
                    }else{
                        //进行关闭操作
                        $auth->removeChild($rule_permission,$menu_permission);
                        $result = '关闭啦';
                        $ajaxObject->content = $result;
                    }
                }else{
                    $result = '失败啦';
                    $ajaxObject->content = $result;
                }
                return $ajaxObject;
            }
        }
    }

    public function getMenuPermission($id){
        $menu_cache = Fun::cache('menu_branch_cache');
        if(isset($menu_cache[$id])){
            $menu_info=$menu_cache[$id];
            $str=!empty($menu_info['m'])?$menu_info['m'].'_'.$menu_info['c'].'_'.$menu_info['a']:$menu_info['c'].'_'.$menu_info['a'];
            if(!empty($menu_info['param'])){
                $param=Util::param2array($menu_info['param']);
                foreach($param as $k=>$v){
                    if(strpos($v,'$') == false){
                        if(isset(\Yii::$app->params['url_param'])) {
                            $str .= in_array($k, \Yii::$app->params['url_param']) ? '_' . $v : '';
                        }
                    }
                }
            }
            if(!empty($str)){
                $auth = \Yii::$app->authManager;
                $permission = $auth->getPermission($str);
                return $permission;
            }else{
                return null;
            }

        }
    }
}